package com.zhengxing.jienci.redis.config;

import java.util.List;

import org.redisson.Redisson;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Cluster;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 * @author 浪遏飞舟
 * @create 2020-06-12 15:57
 */
@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<Object, Object> myRedisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory);
		Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
		template.setDefaultSerializer(ser);
		return template;
	}

	@ConditionalOnProperty(prefix = "spring.redis", name = "model", havingValue = "cluster")
	@Bean
	public Redisson redissonCluster(RedisProperties redisProperties) {
		Cluster cluster = redisProperties.getCluster();
		List<String> nodes = cluster.getNodes();
		Config config = new Config();
		ClusterServersConfig clusterServers = config.useClusterServers();
		nodes.forEach(node -> {
			String addresses = "redis://" + node;
			clusterServers.addNodeAddress(addresses);
		});
		System.out.println("初始化集群");
		return (Redisson) Redisson.create(config);
	}

	@ConditionalOnProperty(prefix = "spring.redis", name = "model", havingValue = "single")
	@Bean
	public Redisson redissonSingle(RedisProperties redisProperties) {
		Config config = new Config();
		String host = redisProperties.getHost();
		int port = redisProperties.getPort();
		String address = "redis://" + host + ":" + port;
		config.useSingleServer().setAddress(address);
		return (Redisson) Redisson.create(config);
	}

	@ConditionalOnProperty(prefix = "spring.redis", name = "model",havingValue = "auto", matchIfMissing = true)
	@Bean
	public Redisson redisson(RedisProperties redisProperties) {
		Config config = new Config();
		Cluster cluster = redisProperties.getCluster();
		if (cluster != null) {
			List<String> nodes = cluster.getNodes();
			ClusterServersConfig clusterServers = config.useClusterServers();
			nodes.forEach(node -> {
				String addresses = "redis://" + node;
				clusterServers.addNodeAddress(addresses);
			});
		} else {
			String host = redisProperties.getHost();
			int port = redisProperties.getPort();
			String address = "redis://" + host + ":" + port;
			config.useSingleServer().setAddress(address);
		}
		return (Redisson) Redisson.create(config);
	}

}
